package org.boot.ssm.wxshop.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @program: wxshop
 * @description: 文件上传工具
 * @author: Parasomnia
 * @create: 2018-03-13 16:33
 **/
public class UploadUtil {
    /**
     * 文件上传
     * @param file 从SpringMVC获取到的上传文件
     * @param request 当前的HTTP请求
     * @param path 希望上传的文件夹路径
     * @return
     */
    public static String fileUpload(HttpServletRequest request,MultipartFile file,String path) {
        String newName = null;
        try {
            String uploadPath = request.getServletContext().getRealPath(path);//上传路径
            File tempPath = new File(uploadPath);
            if(!tempPath.exists()){
                tempPath.mkdirs();
            }
            newName = getName(file.getOriginalFilename());
            File target = new File(uploadPath,newName);
            file.transferTo(target);
        } catch (IOException e) {
            throw new RuntimeException("文件上传组件出现异常！");
        }
        return path+"/"+newName;
    }

    /**
     * 获取文件生成UUID新名字
     * @param name 原名
     * @return
     */
    private static String getName(String name){
        String suffix = name.substring(name.lastIndexOf("."));
        return UUID.randomUUID().toString()+suffix;
    }

}
